<?php
@session_start();
$user_name = '';
$remember = 0;
include_once 'includes/main.inc.php';
if (isset($_POST['login'])) {
	$user_name = $_POST['user_name'];
	$password = $_POST['password'];
	if (isset($_POST['remember'])) {
		$remember = 1;
	}
	if (($user_name == USER_NAME) && (md5($password) == USER_PASS)) {
		if (isset($_POST['remember'])) {
			$expire = time() + 60 * 60 * 24 * 30;//a month
			setcookie('remember', 1, $expire);
			setcookie('token', USER_PASS, $expire);
		} else {
			setcookie('remember', 0, -1);
			setcookie('token', '', -1);
		}
		login_success();
	}
} elseif (isset($_COOKIE['remember'])) {
	if (isset($_COOKIE['token']) && ($_COOKIE['token'] == USER_PASS)) {
		login_success();
	}
}
?>
<form name="login" method="post">
	<fieldset>
	<legend>Login</legend>
	<label>User name:</label> <input type="text" name="user_name" value="<?php echo $user_name;?>" />
	<label>Password:</label> <input type="password" name="password" /><br />
	<input type="submit" name="login" value="Login" /> <input type="checkbox" name="remember" value="1"<?php echo ($remember == 1 ? ' checked' : '')?>>Remember me</input>
	</fieldset>
</form>
<?php 
	function login_success() {
		include_once 'includes/mysql_connect.php';
		$word_table_name = WORD_TABLE_NAME;
		$word_meta_table_name = WORD_META_TABLE_NAME;
		$sql = "SELECT COUNT(*),SUM(word_meta.meta_value) FROM `{$word_table_name}` word
			LEFT JOIN `{$word_meta_table_name}` word_meta
			ON word.id=word_meta.word_id
			AND (word_meta.meta_key='check_correct' OR word_meta.meta_key='check_incorrect');";
		$result = mysql_query($sql, $con);
		if (!$result) {
			die('Could not run query ' . mysql_error());
		}
		$row = mysql_fetch_row($result);
		$word_count = $row[0];
		$word_review = $row[1];
		$_SESSION['user'] = USER_NICE_NAME;
		$_SESSION['word_count'] = $word_count;
		$_SESSION['word_review'] = $word_review;
		$page = 'index.php';
		if (isset($_REQUEST['redirect'])) {
			$page = $_REQUEST['redirect'];
		}
		header("Location: {$page}");
	}
?>